package com.slipper.interceptor;

import com.slipper.common.bo.UserDetail;
import com.slipper.constants.Constants;
import com.slipper.exception.NotLoginException;
import com.slipper.util.Tool;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 登录验证过滤器
 */
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull Object handler) throws Exception {
        try {
            String relativePath = Tool.getRelativePath(request);
            UserDetail userDetail = Constants.getCurrentUser();
            if (!userDetail.isSuperAdmin()
                    && (relativePath.startsWith("/system/")
                        || relativePath.startsWith("/druid/")
                        || relativePath.startsWith("/actuator/"))) {
                request.getRequestDispatcher("/error/forbidden").forward(request, response);
                return false;
            }
            return true;
        } catch (NotLoginException e) {
            request.getRequestDispatcher("/error/notLogin").forward(request, response);
            return false;
        }
    }
}
